const { Controller } = require("egg");

class TopicLessonPersonController extends Controller {
  async list() {
    const { lessonId } = this.ctx.query;
    if (!lessonId) {
      return this.ctx.helper.error("lessonId");
    }
    try {
      const datas = await this.service.topicLessonPerson.list(this.ctx.helper.toInt(lessonId)
      );

      const ids = datas.map(user => user.userId);
      const users = await this.service.user.findUsersByIds(ids)
      users.forEach(element => {
        const another = datas.find(user => user.userId === element.id);
        element = Object.assign(element, another);
      });
      this.ctx.helper.success(users);
    } catch (error) {
      console.log(error, "error")
      this.ctx.helper.error("获取视频列表失败：" + error);
    }
  }

  async bind() {
    const { lessonId, userIds } = this.ctx.request.body;
    if (!lessonId) {
      return this.ctx.helper.error("参数异常：缺少lessonId");
    }
    if (!Array.isArray(userIds)) {
      return this.ctx.helper.error("参数异常：缺少userIds");
    }
    try {
      const createUsers = await this.service.topicLessonPerson.create(lessonId, userIds);
      if (!createUsers) {
        return this.ctx.helper.error("课程不存在或者会员不存在");
      }
      this.ctx.helper.success(createUsers, "课程添加会员成功");
    } catch (error) {
      this.ctx.helper.error("课程添加会员失败" + error.message);
    }
  }


  async delete() {
    const { userId, lessonId } = this.ctx.request.body;
    if (!userId || !lessonId) {
      return this.ctx.helper.error("参数异常：缺少用户id");
    }
    try {
      const deleted = await this.service.topicLessonPerson.delete({ userId, lessonId });
      if (!deleted) {
        return this.ctx.helper.error("会员不存在或删除失败");
      }
      this.ctx.helper.success(deleted, "会员和课程已解除绑定");
    } catch (error) {
      this.ctx.helper.error("会员和课程解除绑定失败" + error.message);
    }
  }

}

module.exports = TopicLessonPersonController;